package com.sad.jetpack.v1.datamodel.demo.testFuture;

import android.net.Uri;
import android.text.TextUtils;

import com.sad.jetpack.v1.datamodel.api.IDataModelChainInput;
import com.sad.jetpack.v1.datamodel.api.IDataModelInterceptorInput;
import com.sad.jetpack.v1.datamodel.api.IDataModelRequest;

import org.json.JSONObject;

import java.util.Iterator;

public class DJXGInputInterceptor implements IDataModelInterceptorInput<String> {
    private final static String PROJECT_CODE="515f5f6fa4aa4735b0b85bfe3ebd3323";
    private final static String PRE_SECRET="e3e90d0c1a824f458611d529ac8c0552";
    @Override
    public void onInterceptedInput(IDataModelChainInput<String> chainInput) throws Exception {
        IDataModelRequest request=chainInput.request();
        IDataModelRequest.Method method=request.method();
        IDataModelRequest.Creator requestCreator=request.toCreator();
        String body=request.body();
        String url=request.url();
        String ts=System.currentTimeMillis()/1000+"";
        requestCreator
                .addHeader("projectCode",PROJECT_CODE)
                .addHeader("secret",getSecret(PROJECT_CODE,PRE_SECRET,ts))
                .addHeader("reqTime",ts);

        if (method== IDataModelRequest.Method.GET){
            //接下来将字典配置给url
            Uri uri=Uri.parse(url);
            Uri.Builder b=uri.buildUpon();

            if (!TextUtils.isEmpty(body)){
                JSONObject json=new JSONObject(body);
                Iterator<String> ks=json.keys();
                while (ks.hasNext()){
                    String k=ks.next();
                    Object v=json.opt(k);
                    b.appendQueryParameter(k,v+"");
                }
            }
            String u_p=b.build().toString();
            requestCreator.url(u_p);
        }
        request=requestCreator.create();
        chainInput.proceed(request,null,chainInput.currIndex());
    }

    @Override
    public String tag() {
        return "徐刚接口专用拦截器";
    }
    private String getSecret(String projectCode,String preSecret,String ts){
        String s=projectCode+ts+preSecret;
        return DataUtils.EncodeToMD5(s.getBytes());
    }
}
